package com.tre.jdevtemplateboot.config;

import com.tre.jdevtemplateboot.common.util.IpConfig;
import com.tre.jdevtemplateboot.common.util.ProjectPomUtils;
import com.tre.jdevtemplateboot.common.util.YamlConfigurerUtil;
import com.tre.jdevtemplateboot.domain.bo.HostsConfig;
import com.tre.jdevtemplateboot.domain.bo.ProjectPom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author JDev
 */
@Configuration
public class YamlConfig {

    private static final Logger logger = LoggerFactory.getLogger(YamlConfig.class);

    @Autowired
    private RestTemplate restTemplate;

    @Bean
    public YamlConfigurerUtil ymlConfigurerUtil() {
        YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
        yamlPropertiesFactoryBean.setResources(new ClassPathResource("application.yml"));
        Properties properties = yamlPropertiesFactoryBean.getObject();
        return new YamlConfigurerUtil(properties);
    }

    @Bean
    public void indexRequestBuilder() {
        if(YamlConfigurerUtil.getStrYmlVal("spring.profiles.active") != null
                && "dev".equals(YamlConfigurerUtil.getStrYmlVal("spring.profiles.active"))){
            HostsConfig ipConfig = IpConfig.getHostsConfig();
            ProjectPom projectPom = ProjectPomUtils.queryPom();
            Map<String, String> jsonMap = new HashMap<>(16);
            jsonMap.put("groupId", projectPom.getGroupId());
            jsonMap.put("artifactId", projectPom.getArtifactId());
            jsonMap.put("version", projectPom.getVersion());
            jsonMap.put("packaging", projectPom.getPackaging());
            jsonMap.put("javaVersion", projectPom.getJavaVersion());
            jsonMap.put("jdevSecurityVersion", projectPom.getJdevBootCoreVersion());
            jsonMap.put("hostsName", ipConfig.getHostsName());
            jsonMap.put("hostsAddress", ipConfig.getHostsAddress());
            jsonMap.put("macAddress", ipConfig.getMacAddress());
            try{
                restTemplate.postForObject("http://172.17.5.87:8093/jdev-es/access/es",jsonMap,Map.class);
                logger.info("indexResponseBuilder -> jdev-es/access/es");
            }
            catch (Exception ex){
                logger.error("indexRequestBuilder -> jdev-es/access/es");
            }
        }
    }
}
